import 'package:flutter/material.dart';
import 'package:ddframework/global/global.dart';

/// 简单toast方案
/// 提供默认文本toast + [时长] + [是否阻塞用户交互]
/// 提供自定义[child]，用于展现自定义toast。（如果存在child会忽略msg）
class DDToast {
  static showToast(
    String message, {
    int millisecond = 2000,
    bool block = false,
    Widget? child,
  }) {
    _show(Global.rootContext, msg: message, millisecond: millisecond, block: block, child: child);
  }

  static _show(
    BuildContext ctx, {
    required String msg,
    int millisecond = 2000,
    bool block = false,
    Widget? child,
  }) {
    final state = Overlay.of(ctx);
    var toast = DDToastWidget(
      block: block,
      msg: msg,
      millisecond: millisecond,
      child: child,
    );
    OverlayEntry entry = OverlayEntry(
      builder: (context) {
        return toast;
      },
    );
    toast.complete = () {
      entry.remove();
    };
    state?.insert(entry);
  }
}

// ignore: must_be_immutable
class DDToastWidget extends StatefulWidget {
  final String msg;
  final int millisecond;
  final bool block;
  final Widget? child;
  Function()? complete;
  DDToastWidget({
    Key? key,
    required this.msg,
    this.millisecond = 2000,
    this.block = false,
    this.child,
    this.complete,
  }) : super(key: key);

  @override
  _DDToastWidgetState createState() => _DDToastWidgetState();
}

class _DDToastWidgetState extends State<DDToastWidget> with TickerProviderStateMixin {
  AnimationController? _animationController;
  Animation<double>? _ani;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _ani = CurvedAnimation(
      parent: _animationController!,
      curve: Curves.easeOut,
    )..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          Future.delayed(
            Duration(milliseconds: widget.millisecond),
          ).then((value) {
            _animationController!.reverse();
          });
        } else if (status == AnimationStatus.dismissed) {
          if (widget.complete != null) {
            widget.complete!();
          }
        }
      });
    _animationController!.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.block ? Color(0x00) : null,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedBuilder(
            animation: _ani!,
            builder: (BuildContext context, Widget? child) {
              return Opacity(
                opacity: _ani!.value,
                child: widget.child ??
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(4),
                        ),
                        color: Colors.black54,
                      ),
                      padding: EdgeInsets.only(
                        top: 4,
                        bottom: 4,
                        left: 8,
                        right: 8,
                      ),
                      margin: EdgeInsets.all(20),
                      child: Text(
                        widget.msg,
                        style: TextStyle(
                          color: Colors.white.withAlpha((_ani!.value * 255.0).toInt()),
                          fontSize: 14,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
              );
            },
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _animationController!.dispose();
    super.dispose();
  }
}
